/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */

package com.simon.mengkou.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;

import com.ouertech.android.agm.lib.base.utils.UtilLog;
import com.ouertech.android.agm.lib.base.utils.UtilString;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;


/**
 * @author : Zhenshui.Xia
 * @date   :  2015年1月13日
 * @desc   : 缩略图工具类
 */
public class UtilThumbnial {
	/**
	 * 获取缩略图
	 * @param source
	 * @param targetSize
	 * @return
	 */
	public static Bitmap createThumbnail(Bitmap source, int targetSize) {
		if(source == null || targetSize <=0) {
			return null;
		}
		
		int oldW = source.getWidth();
		int oldH = source.getHeight();
      
		int w = Math.round((float)oldW/targetSize);  //targetSize为缩略图最大尺寸
		int h = Math.round((float)oldH/targetSize);
      
		
		if(w <= 1 && h <= 1){
			return source;
		}
      
		int i = w > h ? w : h;  //获取缩放比例
      
		int newW = oldW/i;
		int newH = oldH/i;
      
		return ThumbnailUtils.extractThumbnail(source, newW, newH);
	}
	
	
	/**
	 * 获取缩略图
	 * @param data
	 * @param targetSize
	 * @param maxPixels
	 * @return
	 */
	public static Bitmap createThumbnail(byte[] data, int targetSize, int maxPixels) {
		if(data == null || targetSize <=0 || maxPixels <=0) {
			return null;
		}
		
		Bitmap bitmap = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(data, 0, data.length, options);
            if (options.mCancel || options.outWidth == -1
                    || options.outHeight == -1) {
                return null;
            }
            options.inSampleSize = computeSampleSize(
                    options, targetSize, maxPixels);
            options.inJustDecodeBounds = false;

            options.inDither = false;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        } catch (OutOfMemoryError oom) {
            UtilLog.e("Unable to decode data OutOfMemoryError.");
        } finally {
            
        }
        
        return bitmap;
	}
	
	/**
	 * 获取缩略图
	 * @param filePath
	 * @param targetSize
	 * @param maxPixels
	 * @return
	 */
	public static Bitmap createThumbnail(String filePath, int targetSize, int maxPixels) {
		if(UtilString.isBlank(filePath)
				|| targetSize <=0 || maxPixels <=0) {
			return null;
		}
		
		Bitmap bitmap = null;
		FileInputStream stream = null;
        try {
            stream = new FileInputStream(filePath);
            FileDescriptor fd = stream.getFD();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(fd, null, options);
            if (options.mCancel || options.outWidth == -1
                    || options.outHeight == -1) {
                return null;
            }
            options.inSampleSize = computeSampleSize(
                    options, targetSize, maxPixels);
            options.inJustDecodeBounds = false;

            options.inDither = false;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            bitmap = BitmapFactory.decodeFileDescriptor(fd, null, options);
        } catch (IOException ex) {
            UtilLog.e(ex.getMessage());
        } catch (OutOfMemoryError oom) {
            UtilLog.e("Unable to decode file " + filePath + ". OutOfMemoryError.");
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException ex) {
                UtilLog.e(ex.getMessage());
            }
        }
        
        return bitmap;
	}
	
	private static final int UNCONSTRAINED = -1;
	
	private static int computeSampleSize(BitmapFactory.Options options,
            int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8 ) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,
            int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 :
                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == UNCONSTRAINED) ? 128 :
                (int) Math.min(Math.floor(w / minSideLength),
                Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }

        if ((maxNumOfPixels == UNCONSTRAINED) &&
                (minSideLength == UNCONSTRAINED)) {
            return 1;
        } else if (minSideLength == UNCONSTRAINED) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }
    
}
